package kr.co.shoppingmall.shop;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/shop")
public class ShopController {
    @Resource
    private ShopService shopService;

    @RequestMapping("/list.htm")
    public String list(HttpServletRequest request, Model model) {
	String category = (String) request.getParameter("category");
	if (category == null) {
	    category = "tee";
	}
	int count = shopService.getProductCount(category);
	List<ShopDTO> list = shopService.getProductList(category);
	model.addAttribute("product", list);
	model.addAttribute("count", count);
	return "/shop/list";
    }

    @RequestMapping("/detail.htm")
    public String detail(String prodCode, HttpServletRequest request) {
	ShopDTO dto = shopService.getProductDetail(prodCode);
	request.setAttribute("product", dto);
	return "/shop/detail";
    }

    @RequestMapping("/order.htm")
    public String order(HttpSession session, HttpServletRequest request) {
	String id = (String) session.getAttribute("id");
	if (id == null) {
	    return "redirect:/shop/list.htm";
	} else {
	    String code = request.getParameter("prodCode");
	    Integer quantity = Integer.parseInt(request.getParameter("quantity"));
	    System.out.println("id:" + id + ",code:" + code + ",quantity:" + quantity);
	    PurchasedDTO dto = new PurchasedDTO();
	    dto.setPurMemId(id);
	    dto.setPurProdCode(code);
	    dto.setPurQuantity(quantity);
	    shopService.order(dto);
	}
	return "/shop/order";
    }

    @RequestMapping("/cart.htm")
    public String cart(String prodCode, int quantity, HttpSession session, HttpServletRequest request) {
	session.setAttribute(prodCode, quantity);
	List<ShopDTO> list = new ArrayList<ShopDTO>();
	List<Integer> quantityList = new ArrayList<Integer>();
	Enumeration<String> en = session.getAttributeNames();
	while (en.hasMoreElements()) {
	    String code = en.nextElement();
	    if (!code.equals("javax.servlet.jsp.jstl.fmt.request.charset")) {
		ShopDTO dto = shopService.getProductDetail(code);
		list.add(dto);
		Integer su = (Integer) session.getAttribute(prodCode);
		quantityList.add(su);
	    }
	}
	request.setAttribute("list", list);
	request.setAttribute("quantityList", quantityList);
	return "/shop/cart";
    }

    @RequestMapping("purchasedList.htm")
    public String purchased(Model model, HttpSession session) {
	String memId = (String) session.getAttribute("memId");
	List<PurchasedDTO> list = shopService.getPurchasedList(memId);
	model.addAttribute("p", list);
	return "/shop/purchasedList";
    }
}
